(provide 'tm-check)

; Apply the single given check function to the given single entity
; or list of entities and print the results out nicely for interactive
; use. The association list of entities and errors
; is not returned (for readability), instead it is assigned to the
; variable tm-check-errors (this function is really only intended for
; interactive use).

(define tm-check-errors '())

(define (apply-tm-check check-fn ents)
  (if (entity? ents) (set! ents (list ents)))
  (let ((result (apply append
		       (map (lambda (ent)
			      (format #t "Checking entity ~a: " ent)
			      (let ((errors (check-fn ent)))
				(if (not (null? errors))
				    (begin
				      (format #t "~a error(s) found\n" (length errors))
				      (map (lambda (err)
					     (format #t "\t")
					     (tm-chk-info:print err)) errors)
				      (list (cons ent errors)))
				    (begin
				      (format #t "no errors found\n")
				      '()))))
			    ents))))
    (set! tm-check-errors result)
    (let ((num-errors (length result)))
      (format #t "~a entities had errors, ~a entities passed\n" num-errors
	      (- (length ents) num-errors)))))

; Apply the given single tedge check to all the tedges associated
; with the given single entity.

(define (apply-tm-check-tedges check-fn ent)
  (apply-tm-check check-fn (entity:tedges ent)))

; Apply the given single tcoedge check to all the tcoedges associated
; with the given single entity.

(define (apply-tm-check-tcoedges check-fn ent)
  (apply-tm-check check-fn (entity:tcoedges ent)))


; Force recomputation of the tolerances all the given TEDGEs. Pass an
; 2nd argument to get a report of each tolerance as it is computed.

(define (tm:recompute ents . report)
  (if (entity? ents) (set! ents (entity:tedges ents)))
  (map (lambda (e)
	 (let ((tol (edge:get-tolerance e #t)))
	   (if (not (null? report)) (format #t "Tolerance: ~a\n" tol))
	   tol)) ents))
